﻿/**
 * Copyright (C) 2013 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Binder;
using NGuice.Inject.Internal.Util;

namespace NGuice.Inject.Internal
{
    /// <summary>
    /// C#泛型没有通配符，使用标记接口解决通配符问题
    /// </summary>
    public interface ExposureBuilder : IAnnotatedElementBuilder 
    {
        Key Key
        {
            get;
        }

        object Source
        {
            get;
        }
    }

    /// <summary>
    /// 用于私有的绑定器的expose()方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ExposureBuilder<T> : ExposureBuilder
    {
        private readonly IBinder binder;

        private readonly object source;

        private Key<T> key;

        public ExposureBuilder(IBinder binder, object source, Key<T> key)
        {
            this.binder = binder;
            this.source = source;
            this.key = key;
        }

        protected void CheckNotAnnotated()
        {
            if (key.AttributeType != null)
            {
                binder.AddError(AbstractBindingBuilder<T>.ANNOTATION_ALREADY_SPECIFIED);
            }
        }

        public void AnnotatedWith(Type annotationType)
        {
            Preconditions.CheckNotNull(annotationType, "annotationType");
            CheckNotAnnotated();
            key = Key<T>.Get(annotationType);
        }

        public void AnnotatedWith<T>() where T : Attribute
        {
            AnnotatedWith(typeof(T));
        }

        public void AnnotatedWith(Attribute annotation)
        {
            Preconditions.CheckNotNull(annotation, "annotation");
            CheckNotAnnotated();
            key = Key<T>.Get(annotation);
        }

        public Key<T> Key
        {
            get { return key; }
        }

        public object Source
        {
            get { return source; }
        }

        public override string ToString()
        {
            return "AnnotatedElementBuilder";
        }

        Key ExposureBuilder.Key
        {
            get { return Key; }
        }
    }
}
